package xyz.xiaomuyu.moment_read_app.ui.login;

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;

import xyz.xiaomuyu.moment_read_app.R;
import xyz.xiaomuyu.moment_read_app.util.DBUtil;
import xyz.xiaomuyu.moment_read_app.util.TimeUtil;

public class RegisterActivity extends AppCompatActivity {
    private EditText editTextUserName;
    private EditText editTextPassword;
    private EditText editTextPassword1;

    private Button registerButton;
    private String userName;
    private String password;
    private String userImageString;
    private byte[] byteArray;

    private ProgressDialog registerDialog;


    private static final int REGISTER_SUCCESS = 101;//注册成功
    private static final int REGISTER_FAILED_1 = 102;//注册失败，用户名已经存在
    private static final int REGISTER_FAILED_2 = 103;//注册失败
    private static final int MAXSIZE = 35;

    /*
      设置handler接收网络线程的信号并处理
     */
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case REGISTER_SUCCESS:
                    Toast.makeText(getApplicationContext(), "注册成功！", Toast.LENGTH_SHORT).show();
//                    registerDialog.dismiss();
                    Intent intent = new Intent(RegisterActivity.this, LoginActivity.class);
//                    intent.putExtra("userId", userId);
//                    intent.putExtra("userName", userName);
                    startActivity(intent);
                    finish();
                    break;
                case REGISTER_FAILED_1:
                    Toast.makeText(getApplicationContext(), "该用户名已经存在，请重新设置用户名！", Toast.LENGTH_SHORT).show();
                    registerDialog.dismiss();
                    break;
                case REGISTER_FAILED_2:
                    Toast.makeText(getApplicationContext(), "对不起，注册失败！", Toast.LENGTH_SHORT).show();
                    registerDialog.dismiss();
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
//        ImmersionBar.with(this).init();
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        initView();
        //为注册控件响应事件
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!judgeInfo()) {
                    Toast.makeText(getApplicationContext(), "注册信息不完整，请完善注册信息", Toast.LENGTH_LONG).show();
                } else if (!checkPassword()) {
                    Toast.makeText(getApplicationContext(), "两次密码输入不一致，请重新输入密码", Toast.LENGTH_LONG).show();
                } else {
                    register();
                }
            }
        });
    }

    public void initView() {
        editTextUserName = (EditText) findViewById(R.id.m_register_user_name);
        editTextPassword = (EditText) findViewById(R.id.m_register_password);
        editTextPassword1 = (EditText) findViewById(R.id.m_register_check_password);
        registerButton = (Button) findViewById(R.id.m_register_button);
        registerDialog = new ProgressDialog(RegisterActivity.this);
        @SuppressLint("ResourceType")
        Bitmap userImage = BitmapFactory.decodeStream(this.getResources().openRawResource(R.drawable.github));
        ByteArrayOutputStream byStream = new ByteArrayOutputStream();
        //将图片压缩成质量为100的JPEG格式图片
        int option = 10;
        userImage.compress(Bitmap.CompressFormat.JPEG, option, byStream);
        while (byStream.toByteArray().length / 1024 > MAXSIZE) {
            byStream.reset();
            option -= 10;
            userImage.compress(Bitmap.CompressFormat.JPEG, option, byStream);
        }

        //把输出流转换成二进制数组
        byteArray = byStream.toByteArray();
        userImageString = Base64.encodeToString(byteArray, Base64.DEFAULT);
    }

    public boolean judgeInfo() {
        userName = editTextUserName.getText().toString().trim();
        password = editTextPassword.getText().toString().trim();


        // 任何有信息没有填充完毕就直接报错
        return !TextUtils.isEmpty(userName) && !TextUtils.isEmpty(password);
    }

    public boolean checkPassword() {
        password = editTextPassword.getText().toString().trim();
        String temp = editTextPassword1.getText().toString().trim();
        if (!password.equals(temp)) {
            return false;
        }
        return true;
    }

    public void register() {
        /*
        设置登录等待框
         */
        registerDialog.setCanceledOnTouchOutside(false);
        registerDialog.setMessage("正在注册...");
        registerDialog.show();

        /*
        建立网络线程进行登录检查
         */
        final Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //线程间的沟通准备
                try {
                    Message message = new Message();
                    Connection connection = DBUtil.getConn();
                    Statement statement = connection.createStatement();
                    ResultSet resultSet;
                    String querySql = "select * from user where user_name = '" + userName + "'";
                    System.out.println(querySql);
                    resultSet = statement.executeQuery(querySql);
                    System.out.println(querySql);
                    if (resultSet.next()) {
                        message.what = REGISTER_FAILED_1;
                        handler.sendMessage(message);
                    } else {
//                        Date date = new Date();
//                        System.out.println(date);
//                        System.out.println(date.getTime());

                        String insertSql = "insert into user( user_name,password,head_id,create_time) values('"
                                + userName + "','" + password + "','" + userImageString + "','" + TimeUtil.getNowDate() + "');";
                        System.out.println(insertSql);
                        int count = statement.executeUpdate(insertSql);
                        if (count > 0) {
                            message.what = REGISTER_SUCCESS;
                            handler.sendMessage(message);
                        } else {
                            message.what = REGISTER_FAILED_2;
                            handler.sendMessage(message);
                        }
                    }
                    resultSet.close();
                    statement.close();
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        });
        thread.start();
        try {
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}